<!-- home -->
<template>
  <div>
    <van-nav-bar title="详情" left-arrow :fixed="true" :placeholder="true" @click-left="$router.go(-1)" />
    <div class="index-container">
      <div class="video-box">
        <video-player
          class="video-player-box"
          ref="videoPlayer"
          :options="playerOptions"
          :playsinline="true"
        >
        </video-player>
      </div>
      <div class="title-box">
        <div class="title">{{info.name}}</div>
        <div class="edit-box">
          <van-icon :name="isLike ? 'like':'like-o'" :color="isLike ? '#ff9235' : '#999'" @click="handleLike"></van-icon>
          <van-icon :name="isSave ? 'star':'star-o'" :color="isSave ? '#ff9235' : '#999'" @click="handleSave"></van-icon>
        </div>
      </div>
      <div class="com-box">
        <div class="com-title">课程简介</div>
        <div class="content">{{info.desc}}</div>
      </div>
      <div class="com-box">
<!--        <div class="com-title">其他课程</div>-->
        <div class="com-title">课时列表</div>
        <div class="course-box" v-if="isBuyThisCourse">
          <van-tag type="primary" v-for="item,index in courseList" :key="index" size="large" :plain="courseIndex==index?false:true" @click="changeTag(item, index)">{{item.name}}</van-tag>
        </div>
        <div class="course-box" v-else>
          <van-tag color="gray" v-for="item,index in courseList" :key="index" size="large" :plain="courseIndex==index?false:true">{{item.name}}</van-tag>
        </div>
      </div>
      <div class="com-box">
        <div class="com-title">相关推荐</div>
        <div class="video-list-box">
          <van-list
              v-model="listVideo.loading"
              :finished="listVideo.finished"
              finished-text="没有更多了"
              @load="fetchVideoList"
            >
              <div class="item-video-box" @click="goDetailsCourse(item)" v-for="item,index in listVideo.list" :key="index">
                <div class="img-box">
                  <img :src="item.url">
                  <template v-if="!item.isBuy">
                    <van-tag color="#ff3535" v-if="item.price">付费</van-tag>
                    <van-tag color="#35ff4e" v-else>免费</van-tag>
                  </template>
                  <template v-else><van-tag color="#35ff4e">已购买</van-tag></template>
                </div>
                <div class="info-box">
                  <div class="title">{{item.name}}</div>
                  <div class="info">{{item.desc}}</div>
                  <div class="edit-box">{{item.createdAt}}</div>
                </div>
              </div>
            </van-list>

            <div class="item-header" style="text-align: center;font-size: 14px;">没有更多了..</div>
        </div>
      </div>
    </div>

      <van-submit-bar label="价格" :price="info.price" :button-text="info.price == 0 ? '立即报名' : '立即购买'" @submit="onSubmit" v-if="!isBuyThisCourse"/>
      <van-submit-bar label="价格" :price="info.price" button-text="已购买" disabled @submit="onSubmit" v-else/>

  </div>
</template>

<script>
import { likeCourseById,saveCourseById,likeCourseAdd,likeCourseDel,saveCourseAdd,saveCourseDel } from '@/api/course.js'
import { details, list} from '@/api/course.js'
import { courseDetailList } from '@/api/courseDetail.js'
import { alipayTradePrecreate, alipayTradeWapPay, alipayTradeQuery } from '@/api/common.js'
import dayjs from 'dayjs'
import { orderAdd,orderAll } from '@/api/order.js'

export default {
  data() {
    return {
      isBuyThisCourse: false,
      id:null,
      isLike: false,
      isSave: false,
      courseIndex:0,
      userId:null,
      courseOrderList:[],
      info:{},
      courseList:[
        {
          id:0,
          name:'第一节：放点的多少分'
        },
        {
          id:1,
          name:'第二节：方首付是多大'
        },
        {
          id:2,
          name:'第三节：和花港饭店'
        },
        {
          id:3,
          name:'第四节：跳跳哥哥'
        },{
          id:4,
          name:'第五节：机构改革发'
        }
      ],
      listVideo:{
        loading: false,
        finished: false,
        listQuery:{
          pageSize:20,
          pageNum:0,
        },
        list:[]
      },
      playerOptions: {
        // videojs options
        muted: true,
        language: 'en',
        playbackRates: [0.7, 1.0, 1.5, 2.0],
        sources: [{
          type: "video/mp4",
          src: "http://localhost:10086/upload/video.mp4"
        }],
        notSupportedMessage: '此视频暂无法播放，请稍后再试',
        preload: 'auto',
        fluid: true,
        poster: "",
      }

    }
  },

  computed: {},

  mounted() {
    if (this.id) {
      this.getAboutCourse()
    }
  },
  created() {
    this.userId = this.$store.getters.userId
    this.id = Number(this.$route.query.courseId)
    if (this.$route.query.no) {
      this.getTradeQuery({no: this.$route.query.no});
    }
  },

  methods: {
    getAboutCourse() {
      this.fetchDetails()
      this.likeCourseById()
      this.saveCourseById()
      this.fetchCourseDetails()
    },
    async fetchOrderList() {
      await orderAll({userId: Number(this.$store.getters.userId)}).then(res => {
        if (res.code == 200) {
          this.courseOrderList = res.data
          this.listVideo.list.forEach((ite,ind)=>{
            this.courseOrderList.forEach((item,index)=>{
              if(item.courseId == ite.id){
                this.$set(ite,'isBuy',true)
              }
            })
          })
          let orderList = this.courseOrderList.filter(d => d.courseId == this.info.id)
          if (orderList.length > 0) {
            this.isBuyThisCourse = true;
            this.changeTag(this.courseList[0], 0)
          } else {
            this.isBuyThisCourse = false;
            this.playerOptions.sources = [{
              type: "video/mp4",
              src: undefined
            }];
          }
        } else {
          this.$notify(res.message)
        }
      })
    },
    async fetchVideoList() {
      this.listVideo.listQuery.pageNum ++
      await list({...this.listVideo.listQuery, pageSize: 3}).then(res => {
        if (res.code == 200) {
          res.data.rows.map(item => {
            item.createdAt = dayjs(item.createdAt).format('YYYY-MM-DD HH:mm:ss')
          })
          this.listVideo.list = this.listVideo.list.concat(res.data.rows)
          this.listVideo.loading= false
          this.fetchOrderList()
          if(res.data.count > this.listVideo.list.length){
            this.listVideo.finished = false
          }else{
            this.listVideo.finished = true
          }
        } else {
          this.$notify(res.message)
        }
      })
    },
    async fetchDetails(){
      await details({id:this.id}).then(res => {
        if (res.code == 200) {
          this.info= res.data
          // this.info.price = Number(Number(res.data.price).toFixed(2));
          this.info.price = Number(res.data.price) * 100;
          this.playerOptions.poster = res.data.url
          this.fetchOrderList()
        } else {
          this.$notify(res.message)
        }
      })
    },
    // 获取课时列表
    async fetchCourseDetails(){
      await courseDetailList({courseId: this.id}).then(res => {
        if (res.code == 200) {
          this.courseList = res.data.rows
          if (res.data.rows.length > 0) {
            this.changeTag(this.courseList[0], 0)
          } else {
            this.playerOptions.sources = [{
              type: "video/mp4",
              src: undefined
            }];
          }
        } else {
          this.$notify(res.message)
        }
      })
    },
    changeTag(item, index){
      this.courseIndex = index
      this.playerOptions.sources = [{
        type: "video/mp4",
        src: item.url
      }];
    },
    goDetailsCourse(item){
      this.$router.push({
        path:'/videoDetails?courseId='+item.id
      })
      // window.location.replace(`/#/videoDetails?courseId=${item.id}`)
      // window.location.reload();
      this.id = item.id;
      this.getAboutCourse()
    },
    async likeCourseById() {
      await likeCourseById({ courseId: this.id },this.isCourse).then(res => {
        if (res.code == 200) {
          this.countLike = res.data.length
          res.data.forEach((item,index) => {
              if(item.userId == this.userId){
                  this.isLike = true
                  this.likeId = item.id
              }
          });
          let likeList = res.data.filter(dd => dd.userId == this.userId)
          if (likeList.length === 0) {
            this.isLike = false;
          }

        } else {
          this.$notify(res.message)
        }
      })
    },
    async like() {
      await likeCourseAdd({
          courseId: this.id ,
          userId:this.userId},this.isCourse
        ).then(res => {
        if (res.code == 200) {
          this.likeCourseById()
        } else {
          this.$notify(res.message)
        }
      })
    },
    async unlike() {
      await likeCourseDel({
          id: this.likeId },this.isCourse
        ).then(res => {
        if (res.code == 200) {
          this.likeCourseById()
        } else {
          this.$notify(res.message)
        }
      })
    },
    async saveCourseById() {
      await saveCourseById({ courseId: this.id},this.isCourse).then(res => {
        if (res.code == 200) {
          this.countSave = res.data.length
           res.data.forEach((item,index) => {
              if(item.userId == this.userId){
                  this.isSave = true
                  this.saveId = item.id
              }
          });
          let saveList = res.data.filter(dd => dd.userId == this.userId)
          if (saveList.length === 0) {
            this.isSave = false;
          }
        } else {
          this.$notify(res.message)
        }
      })
    },
    async saveCourseAdd() {
      await saveCourseAdd({
          courseId: this.id ,
          userId:this.userId},this.isCourse
        ).then(res => {
        if (res.code == 200) {
          this.saveCourseById()
        } else {
          this.$notify(res.message)
        }
      })
    },
    async saveCourseDel() {
      await saveCourseDel({
          id: this.saveId},this.isCourse
        ).then(res => {
        if (res.code == 200) {
          this.saveCourseById()
        } else {
          this.$notify(res.message)
        }
      })
    },
    handleSave() {
         if(this.isSave){
            this.saveCourseDel()
        }else{
            this.saveCourseAdd()
        }
        this.isSave = !this.isSave
    },
    handleLike() {
        if(this.isLike){
            this.unlike()
        }else{
            this.like()
        }

        this.isLike = !this.isLike
    },
    onSubmit(order = this.info) {
      this.$dialog.confirm({
        message: `确认支付 ￥${order.price / 100} 购买课程吗？`,
      })
        .then(async () => {
          if (order.price == 0) {
            this.handleOrder(this.id)
          } else {
            let obj = {
              no: new Date().getTime(),
              price: order.price / 100,
              subject: order.name,
              courseId: this.id,
            };
            const res = await alipayTradePrecreate(obj);
            if (res.code === 200) {
              this.no = res.data.outTradeNo;
              this.toTradePay({...obj, no: this.no});
            }
          }
        })
        .catch(() => {
          // on cancel
        });
    },
    async handleOrder(id){
      await orderAdd({courseId:id,userId:Number(this.$store.getters.userId), no: new Date().getTime()}).then(res => {
        if (res.code == 200) {
          this.$toast.success('支付成功~');
          setTimeout(()=>{
            this.$toast.clear()
            this.getAboutCourse()
          },1500)
        } else {
          this.$notify(res.message)
        }
      })
    },
    async toTradePay(order) {
      try {
        const res = await alipayTradeWapPay(order);
        this.data = res.data;
        window.location.href = this.data;
      } catch (e) {
        this.data = e
        console.log(e)
      }

      console.log(this.data)
      // document.forms[0].submit()
    },
    async getTradeQuery(no) {
      const res = await alipayTradeQuery(no);
      if (res.code === 200) {
        // this.$toast.success('支付成功~');
        this.isBuy = true;
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.index-container {
  box-sizing: border-box;
  width: 100%;
  min-height: 100vh;
  .com-box{
    background: #fff;
    padding:.4167rem .4444rem ;
    box-sizing: border-box;
    margin-top: .1389rem;
    .course-box{
      .van-tag{
        margin:.1389rem;
      }
    }
    .com-title{
      font-size: .3889rem;
      font-weight: bold;
      margin-bottom: .2778rem;
      border-left: .1rem solid #ff9235;
      padding-left: .2778rem;
      height: .3rem;
      line-height: .3rem;
    }
    .content{
      font-size: .3333rem;
      line-height: .5556rem;
      word-break: break-all;
      color: #333;
    }
  }
  .title-box{
    background: #fff;
    padding:.4167rem 1rem .4444rem .4167rem;
    box-sizing: border-box;
    position: relative;
    width: 100%;
    line-height: .7rem;
    .title{
      font-size: .4722rem;
      font-weight: bold;
    }
    .edit-box{
      position: absolute;
      top: .4167rem;
      bottom: .4167rem;
      right: .18rem;
      font-size: .46rem;
      padding:0 0 0 .2778rem;
        display: flex;
      .van-icon{
        color: #666;
        display: block;
        padding: 0;
        margin:0 10px .4rem 0 ;
        &::before{
          margin-right: .1389rem;
          font-weight: bold;
          color: #ff9235;
        }
      }
    }
  }
  .video-box{
    width: 100%;
    .video-player-box{
      width: 100%;
      position: relative;
      /deep/ .video-js{
        width: 100% !important;
        // height: 5.rem;
      }
      /deep/ .vjs-big-play-button{
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        background-color: #ff9235;
      }
    }
  }
  .video-list-box{
    margin-top: .45rem;
  }
  .item-video-box{
    background: #fff;
    border-radius: .2778rem;
    display: flex;
    align-items: center;
    box-sizing: border-box;
    width: 100%;
    margin:.2778rem auto 0;
    .img-box{
      flex: 0 0 3rem;
      position: relative;
      img{
        width:100%;
        height: 2.2rem;
        border-radius: .1389rem;
      }
      .van-tag{
        position: absolute;
        top: .1389rem;
        left: .1389rem;
      }
    }
    .info-box{
      flex:1;
      padding: .1389rem .1389rem .1389rem .2778rem;
      box-sizing: border-box;
      height: 2.2rem;
      position: relative;
      .title{
        width:5.5rem;
        font-size: .4167rem;
        color: #000;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .info{
        font-size: .3333rem;
        color: #999;
        margin-top: .2rem;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
      }
      .edit-box{
        position: absolute;
        left: .2778rem;
        bottom: .0556rem;
        font-size: .3333rem;
        width: 100%;
        .van-icon{
          min-width: 1.7rem;
          color: #666;
          display: inline-block;
          &::before{
            margin-right: .1389rem;
            font-size: .3333rem;
            font-weight: bold;
            color: #ff9235;
          }
        }
      }
    }
  }
}
</style>
